using System.Net;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using LDNS.Interfaces;
using LDNS.Models;
using LDNS.SDK.Commands.Models;
using LDNS.SDK.Formatting;
using LDNS.Api;
using LDNS.Utilities;
using NLog;
using LDNS.SDK.Commands;

namespace LDNS.Services
{
    /// <summary>
    /// 本地DNS服务实现
    /// 作者：huobing
    /// </summary>
    public class LocalDNSService : IDnsService
    {
        #region 字段和属性
        // 日志记录器
        private readonly Logger _logger = LogManager.GetCurrentClassLogger();
        // UDP客户端用于监听和响应DNS查询
        private UdpClient? _udpClient;
        // 取消令牌源，用于取消监听任务
        private CancellationTokenSource? _cancellationTokenSource;
        // 上游DNS管理器
        private readonly UpstreamDnsManager _upstreamDnsManager;
        // DNS配置管理器
        private readonly DnsConfigManager _dnsConfigManager;
        // 上游域名管理器
        private readonly UpstreamDomainManager _upstreamDomainManager;
        // DNS记录管理器 - 处理所有域名记录相关操作
        private readonly DnsRecordManager _dnsRecordManager;
        // DNS记录统计管理器 - 记录查询统计信息
        private readonly DnsRecordStatistics _recordStatistics = new();
        // DNS服务统计信息
        private readonly DnsStatistics _dnsStatistics = new();
        // 服务配置
        private DnsServiceConfig _config;
        private Task? _listenerTask;
        private bool _isRunning = false;
        private bool _disposed = false;
        private DateTime _startTime = DateTime.MinValue;
        // 访问控制相关字段
        private readonly bool _enableAccessControl = false;
        private readonly List<string> _allowedIps = [];

        /// <summary>
        /// 获取服务是否正在运行
        /// </summary>
        public bool IsRunning => _isRunning;
        
        /// <summary>
        /// 获取服务监听的端口
        /// </summary>
        public int Port => _config.Port;


        /// <summary>
        /// 获取服务运行时间
        /// </summary>
        public TimeSpan GetUptime()
        {
            if (!_isRunning || _startTime == DateTime.MinValue)
            {
                return TimeSpan.Zero;
            }
            return DateTime.Now - _startTime;
        }

        /// <summary>
        /// 获取DNS服务统计信息
        /// </summary>
        /// <returns>DNS服务统计信息</returns>
        public DnsStatistics GetDnsStatistics()
        {
            // 返回统计信息的副本，避免外部直接修改
            return new DnsStatistics
            {
                SuccessfulQueries = _dnsStatistics.SuccessfulQueries,
                FailedQueries = _dnsStatistics.FailedQueries,
                TotalResponseTimeMs = _dnsStatistics.TotalResponseTimeMs,
                QueryTypeDistribution = new Dictionary<string, long>(_dnsStatistics.QueryTypeDistribution)
            };
        }


        /// <summary>
        /// 获取Socket管理器实例
        /// </summary>
        public ISocketManager? SocketService { get; private set; }
        #endregion

        #region 构造函数
        /// <summary>
        /// 构造函数
        /// </summary>
        public LocalDNSService()
        {
            DnsConfigManager configManager = DnsConfigManager.Instance;
            if (configManager == null)
                throw new ArgumentNullException(nameof(configManager));

            _config = configManager.Config;
            // 访问控制配置
            _enableAccessControl = _config.EnableAccessControl;
            if (_enableAccessControl && _config.AllowedIPs != null)
            {
                _allowedIps.AddRange(_config.AllowedIPs);
            }

            // 初始化配置管理器相关字段
            _dnsConfigManager = configManager;
            _upstreamDnsManager = UpstreamDnsManager.Instance;
            _upstreamDomainManager = UpstreamDomainManager.Instance;

            // 如果启用Socket管理，创建Socket管理器
            if (_config.EnableSocketManagement)
            {
                InitializeSocketManager();
            }

            _dnsRecordManager = DnsRecordManager.Instance;
        }
        #endregion

        #region Socket管理相关方法

        /// <summary>
        /// 初始化Socket管理器
        /// </summary>
        private void InitializeSocketManager()
        {
            try
            {
                // 传入当前的LocalDNSService实例，它实现了IDnsService接口
                SocketService = new SocketService(this);
                _logger.Info("Socket管理器初始化成功，命令执行器已配置");
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"初始化Socket管理器失败: {ex.Message}");
                SocketService = null;
            }
        }

        /// <summary>
        /// 启动Socket管理服务
        /// </summary>
        /// <returns>是否启动成功</returns>
        private async Task<bool> StartSocketManagementAsync()
        {
            if (!_config.EnableSocketManagement || SocketService == null)
            {
                return false;
            }

            try
            {
                bool success = await SocketService.StartAsync(_config.SocketManagementPort);
                if (success)
                {
                    _logger.Info($"Socket管理服务已启动，监听端口: {_config.SocketManagementPort}");
                }
                else
                {
                    _logger.Error("Socket管理服务启动失败");
                }
                return success;
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"启动Socket管理服务时发生错误: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 停止Socket管理服务
        /// </summary>
        private void StopSocketManagement()
        {
            if (SocketService != null)
            {
                SocketService.Stop();
                _logger.Info("Socket管理服务已停止");
            }
        }

        /// <summary>
        /// 停止Socket管理服务（异步版本）
        /// </summary>
        private async Task StopSocketManagementAsync()
        {
            if (SocketService != null)
            {
                await SocketService.StopAsync();
                _logger.Info("Socket管理服务已停止");
            }
        }
        #endregion

        #region 公共方法
        /// <summary>
        /// 启动DNS服务
        /// </summary>
        /// <returns>是否启动成功</returns>
        public async Task<bool> StartAsync()
        {
            _logger.Debug("开始执行StartAsync方法");

            if (_isRunning)
            {
                _logger.Info("DNS服务已经在运行中");
                return true;
            }

            try
            {
                _logger.Debug($"准备创建UDP客户端，监听端口: {_config.Port}");

                // 检查端口是否被占用
                try
                {
                    using (var checkClient = new UdpClient(AddressFamily.InterNetwork))
                    {
                        checkClient.Client.Bind(new IPEndPoint(IPAddress.Any, _config.Port));
                        _logger.Debug($"端口 {_config.Port} 可用");
                    }
                }
                catch (SocketException socketEx)
                {
                    _logger.Error(socketEx, $"端口 {_config.Port} 已被占用: {socketEx.Message}");
                    throw new Exception($"端口 {_config.Port} 已被占用: {socketEx.Message}", socketEx);
                }

                // 创建UDP客户端
                _logger.Debug($"正在创建UDP客户端，绑定端口: {_config.Port}");
                _udpClient = new UdpClient(_config.Port, AddressFamily.InterNetwork);
                _logger.Debug($"UDP客户端创建成功，已绑定端口: {_config.Port}");

                _cancellationTokenSource = new();
                _logger.Debug("创建取消令牌源");

                // 启动监听任务
                _logger.Debug("启动DNS请求监听任务");
                _listenerTask = Task.Run(async () => await ListenForDnsRequestsAsync(_cancellationTokenSource.Token));
                _logger.Debug("监听任务已启动");

                // 如果启用Socket管理，启动Socket管理服务
                bool socketStarted = true;
                if (_config.EnableSocketManagement)
                {
                    _logger.Debug($"启用Socket管理，准备启动Socket管理服务，端口: {_config.SocketManagementPort}");
                    socketStarted = await StartSocketManagementAsync();
                    _logger.Debug($"Socket管理服务启动结果: {socketStarted}");
                }

                _isRunning = true;
                _startTime = DateTime.Now; // 记录启动时间

                _logger.Info($"DNS服务已成功启动，监听端口: {_config.Port}");
                _logger.Info($"上游DNS服务器配置: {string.Join(", ", _upstreamDnsManager.GetUpstreamDnsInfos().Select(x => x.Ip))}");

                if (_config.EnableSocketManagement)
                {
                    _logger.Info($"Socket管理服务状态: {(socketStarted ? "已启动" : "启动失败")}");
                }

                try
                {
                    _dnsRecordManager?.StartWatching();
                    _logger.Debug("配置监控已在启动末尾启动");
                }
                catch (Exception ex)
                {
                    _logger.Error(ex, "启动配置监控失败");
                }

                return true;
            }
            catch (Exception ex)
            {
                string errorDetails = $"启动DNS服务失败: {ex.Message}\n{ex.StackTrace}";
                if (ex.InnerException != null)
                {
                    errorDetails += $"\n内部异常: {ex.InnerException.Message}\n{ex.InnerException.StackTrace}";
                }

                _logger.Error(ex, errorDetails);

                try
                {
                    await StopAsync();
                }
                catch (Exception stopEx)
                {
                    _logger.Error(stopEx, "停止服务时发生异常");
                }

                return false;
            }
        }
        /// <summary>
        /// 获取服务启动时间
        /// </summary>
        /// <returns>服务启动时间，如果服务未运行则返回DateTime.MinValue</returns>
        public DateTime GetStartTime()
        {
            if (!_isRunning || _startTime == DateTime.MinValue)
            {
                return DateTime.MinValue;
            }
            return _startTime;
        }

        /// <summary>
        /// 启动DNS服务（同步版本）
        /// </summary>
        /// <returns>是否启动成功</returns>
        public bool Start()
        {
            return StartAsync().GetAwaiter().GetResult();
        }

        /// <summary>
        /// 停止DNS服务
        /// </summary>
        public async Task StopAsync()
        {
            _logger.Debug("开始执行StopAsync方法");

            if (!_isRunning)
            {
                _logger.Debug("服务未运行，无需停止");
                return;
            }

            try
            {
                _logger.Debug("正在停止DNS服务...");

                // 如果启用Socket管理，停止Socket管理服务
                if (_config.EnableSocketManagement && SocketService != null)
                {
                    _logger.Debug("停止Socket管理服务");
                    await StopSocketManagementAsync();
                    _logger.Debug("Socket管理服务已停止");
                }

                _logger.Debug("取消监听任务");
                _cancellationTokenSource?.Cancel();


                // 等待监听任务完成
                if (_listenerTask != null && !_listenerTask.IsCompleted)
                {
                    _logger.Debug("等待监听任务完成");
                    try
                    {
                        await _listenerTask.ContinueWith(t => { }, TaskContinuationOptions.OnlyOnFaulted);
                        _logger.Debug("监听任务已完成");
                    }
                    catch (AggregateException)
                    {
                        _logger.Debug("监听任务取消异常（预期行为）");
                        // 任务取消异常是预期的
                    }
                }

                _logger.Debug("关闭并释放UDP客户端");
                _udpClient?.Close();
                _udpClient?.Dispose();
                _logger.Debug("UDP客户端已关闭");

                _logger.Debug("释放取消令牌源");
                _cancellationTokenSource?.Dispose();

                _logger.Debug("更新服务运行状态为停止");
                _isRunning = false;

                _logger.Info("DNS服务已成功停止");
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"停止DNS服务时发生错误: {ex.Message}");
                _logger.Error($"异常堆栈: {ex.StackTrace}");
                if (ex.InnerException != null)
                {
                    _logger.Error($"内部异常: {ex.InnerException.Message}");
                    _logger.Error($"内部异常堆栈: {ex.InnerException.StackTrace}");
                }

            }
            finally
            {
                _logger.Debug("清理服务资源");
                _udpClient = null;
                _cancellationTokenSource = null;
                _listenerTask = null;
                _logger.Debug("服务资源清理完成");
            }
        }

        /// <summary>
        /// 停止DNS服务（同步版本）
        /// </summary>
        public void Stop()
        {
            StopAsync().GetAwaiter().GetResult();
        }
        #endregion

        #region 私有方法
        /// <summary>
        /// 监听DNS请求
        /// </summary>
        /// <param name="cancellationToken">取消令牌</param>
        private async Task ListenForDnsRequestsAsync(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested && _udpClient != null)
            {
                try
                {
                    // 接收UDP数据包
                    var receiveResult = await _udpClient.ReceiveAsync(cancellationToken);

                    // 处理DNS请求
                    _ = Task.Run(async () => await ProcessDnsRequestAsync(receiveResult.Buffer, receiveResult.RemoteEndPoint), cancellationToken);
                }
                catch (OperationCanceledException)
                {
                    // 正常取消
                    break;
                }
                catch (Exception ex)
                {
                    // 检查是否为"远程主机强迫关闭了一个现有的连接"类型的SocketException
                    if (ex is SocketException socketEx && socketEx.ErrorCode == 10054)
                    {
                        _logger.Info($"远程连接已关闭");
                    }
                    else
                    {
                        _logger.Error(ex, $"处理DNS请求时发生错误: {ex.Message}");
                    }
                    
                    // 异常情况下更新失败计数
                    lock (_dnsStatistics)
                    {
                        _dnsStatistics.FailedQueries++;
                    }
                }
            }
        }

        /// <summary>
        /// 处理DNS请求
        /// </summary>
        /// <param name="requestData">请求数据</param>
        /// <param name="remoteEndPoint">远程端点</param>
        private async Task ProcessDnsRequestAsync(byte[] requestData, IPEndPoint remoteEndPoint)
        {
            // 记录请求开始时间，用于计算响应时间
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            bool isSuccess = false;
            string? domain = null;
            string queryType = string.Empty;
            
            try
            {
                // 解析DNS请求（简化实现）
                domain = DnsDataUtils.ExtractDomainFromDnsRequest(requestData);
                queryType = DnsDataUtils.ExtractQueryTypeFromDnsRequest(requestData);

                if (string.IsNullOrWhiteSpace(domain))
                {
                    _logger.Info($"收到无效DNS请求，来源: {remoteEndPoint}");
                    return;
                }

                // 访问控制：拦截未授权IP
                if (_enableAccessControl)
                {
                    var srcIp = remoteEndPoint.Address;
                    bool allowed = false;

                    // 本地函数：CIDR匹配（支持IPv4/IPv6）
                    static bool IsInCidrLocal(IPAddress ip, string cidr)
                    {
                        try
                        {
                            var parts = cidr.Split('/');
                            if (parts.Length != 2) return false;
                            if (!IPAddress.TryParse(parts[0], out var network)) return false;
                            if (!int.TryParse(parts[1], out var prefixLength)) return false;

                            var ipBytes = ip.GetAddressBytes();
                            var netBytes = network.GetAddressBytes();
                            if (ipBytes.Length != netBytes.Length) return false; // IPv4/IPv6不匹配

                            int fullBytes = prefixLength / 8;
                            int remainderBits = prefixLength % 8;

                            for (int i = 0; i < fullBytes; i++)
                            {
                                if (ipBytes[i] != netBytes[i]) return false;
                            }
                            if (remainderBits > 0)
                            {
                                int mask = 0xFF << (8 - remainderBits);
                                if ((ipBytes[fullBytes] & mask) != (netBytes[fullBytes] & mask)) return false;
                            }
                            return true;
                        }
                        catch
                        {
                            return false;
                        }
                    }

                    // 本地函数：范围匹配（start-end，支持IPv4/IPv6）
                    static bool IsInRangeLocal(IPAddress ip, string range)
                    {
                        try
                        {
                            var parts = range.Split('-', 2);
                            if (parts.Length != 2) return false;
                            if (!IPAddress.TryParse(parts[0].Trim(), out var start)) return false;
                            if (!IPAddress.TryParse(parts[1].Trim(), out var end)) return false;
                            var ipBytes = ip.GetAddressBytes();
                            var startBytes = start.GetAddressBytes();
                            var endBytes = end.GetAddressBytes();
                            if (ipBytes.Length != startBytes.Length || ipBytes.Length != endBytes.Length) return false; // IPv4/IPv6不匹配

                            // 规范化范围顺序
                            int cmpStartEnd = CompareBytes(startBytes, endBytes);
                            if (cmpStartEnd > 0)
                            {
                                var tmp = startBytes; startBytes = endBytes; endBytes = tmp;
                            }

                            // 检查 ip 是否在 [start, end] 范围内
                            return CompareBytes(ipBytes, startBytes) >= 0 && CompareBytes(ipBytes, endBytes) <= 0;

                            // 本地比较函数
                            static int CompareBytes(byte[] a, byte[] b)
                            {
                                for (int i = 0; i < a.Length && i < b.Length; i++)
                                {
                                    int diff = a[i].CompareTo(b[i]);
                                    if (diff != 0) return diff;
                                }
                                return a.Length.CompareTo(b.Length);
                            }
                        }
                        catch
                        {
                            return false;
                        }
                    }

                    if (_allowedIps != null && _allowedIps.Count > 0)
                    {
                        foreach (var rule in _allowedIps)
                        {
                            if (string.IsNullOrWhiteSpace(rule)) continue;
                            if (rule.Contains("/"))
                            {
                                if (IsInCidrLocal(srcIp, rule)) { allowed = true; break; }
                            }
                            else if (rule.Contains("-"))
                            {
                                if (IsInRangeLocal(srcIp, rule)) { allowed = true; break; }
                            }
                            else
                            {
                                if (string.Equals(srcIp.ToString(), rule, StringComparison.OrdinalIgnoreCase)) { allowed = true; break; }
                            }
                        }
                    }

                    if (!allowed)
                    {
                        _logger.Info($"拒绝来自未授权IP的查询: {srcIp}");
                        return;
                    }
                }

                _logger.Info($"收到DNS查询: {domain}，来源: {remoteEndPoint}");

                // 查询统计由DnsCacheManager管理

                // 检查是否为反向解析请求（PTR记录）
                if (domain.EndsWith(".in-addr.arpa") || domain.EndsWith(".ip6.arpa"))
                {
                    // 处理反向解析请求
                    var hostname = await HandleReverseLookupAsync(domain);
                    if (!string.IsNullOrWhiteSpace(hostname))
                    {
                        _logger.Info($"反向解析: {domain} -> {hostname}");
                        // 对于反向解析，我们需要创建特殊的响应
                        var responseData = DnsDataUtils.CreateReverseDnsResponse(requestData, hostname);
                        await _udpClient!.SendAsync(responseData, responseData.Length, remoteEndPoint);

                        return; // 已经处理了响应，直接返回
                    }
                }
                else
                {
                    // 正向解析请求
                    string? resolvedIp = null;
                    List<string>? ipAddresses = null; // 用于存储多个IP地址
                    
                    // 检查缓存
                    var cachedItem = DnsCacheManager.Instance.GetDnsCacheItem(domain);
                    if (cachedItem != null)
                    {
                        resolvedIp = cachedItem.IP;
                        _logger.Info($"从缓存解析: {domain} -> {resolvedIp}");
                        
                        // 尝试获取缓存中的所有IP地址
                        ipAddresses = DnsCacheManager.Instance.GetAllCachedIpsForDomain(domain);
                        if (ipAddresses.Count > 1)
                        {
                            _logger.Info($"从缓存获取多个IP地址: {domain} -> {string.Join(", ", ipAddresses)}");
                        }
                    }

                    // 如果缓存未命中或过期，尝试泛域名解析
                    if (string.IsNullOrWhiteSpace(resolvedIp) && _dnsRecordManager != null)
                    {
                        resolvedIp = _dnsRecordManager.ResolveDomain(domain);
                        if (!string.IsNullOrWhiteSpace(resolvedIp))
                        {
                            // 缓存泛域名解析结果
                            var cacheItem = new LDNS.Models.DnsCacheItem
                            {
                                Domain = domain,
                                IP = resolvedIp,
                                RecordType = "A",
                                Ttl = 3600,
                                Source = "wildcard",
                                CreatedTime = DateTime.Now,
                                LastAccessed = DateTime.Now
                            };
                            DnsCacheManager.Instance.AddDnsCacheItem(domain, cacheItem);
                            _logger.Info($"泛域名解析: {domain} -> {resolvedIp}");
                        }
                    }

                    // 如果泛域名解析未命中，向上游DNS服务器查询
                    if (string.IsNullOrWhiteSpace(resolvedIp))
                    {
                        ipAddresses = await _upstreamDnsManager.QueryUpstreamDnsAllAsync(domain);

                        if (ipAddresses.Count > 0)
                        {
                            // 使用第一个IP地址作为resolvedIp（保持向后兼容）
                            resolvedIp = ipAddresses[0];
                            
                            // 缓存结果（将所有IP地址存储在同一个缓存项中）
                            var cacheItem = new LDNS.Models.DnsCacheItem
                            {
                                Domain = domain,
                                IPs = ipAddresses.Distinct().ToList(), // 去重
                                RecordType = "A",
                                Ttl = 3600,
                                Source = "upstream",
                                CreatedTime = DateTime.Now,
                                LastAccessed = DateTime.Now
                            };
                            DnsCacheManager.Instance.AddDnsCacheItem(domain, cacheItem);
                            
                            // 记录上游DNS服务器与域名的映射关系
                            _upstreamDnsManager.RecordDomainMapping(domain);
                            _logger.Info($"向上游DNS查询: {domain} -> {string.Join(", ", ipAddresses)}");
                        }
                    }

                    // 发送响应（简化实现）
                    if (!string.IsNullOrWhiteSpace(resolvedIp))
                    {
                        // 如果是从缓存获取的IP地址，确保使用缓存中的IP列表
                        if (ipAddresses != null && ipAddresses.Count > 0)
                        {
                            // 确保IP地址列表去重
                            var uniqueIps = ipAddresses.Distinct().ToList();
                            
                            // 如果有多个IP地址，使用所有IP地址
                            if (uniqueIps.Count > 1)
                            {
                                var responseData = DnsDataUtils.CreateDnsResponse(requestData, uniqueIps);
                                await _udpClient!.SendAsync(responseData, responseData.Length, remoteEndPoint);
                                _logger.Info($"发送DNS响应: {domain} -> {string.Join(", ", uniqueIps)}");
                            }
                            else
                            {
                                var responseData = DnsDataUtils.CreateDnsResponse(requestData, uniqueIps[0]);
                                await _udpClient!.SendAsync(responseData, responseData.Length, remoteEndPoint);
                                _logger.Info($"发送DNS响应: {domain} -> {uniqueIps[0]}");
                            }
                        }
                        else
                        {
                            // 如果没有IP地址列表，使用resolvedIp创建单元素列表
                            var responseData = DnsDataUtils.CreateDnsResponse(requestData, resolvedIp);
                            await _udpClient!.SendAsync(responseData, responseData.Length, remoteEndPoint);
                            _logger.Info($"发送DNS响应: {domain} -> {resolvedIp}");
                        }
                        
                        isSuccess = true; // 标记为成功
                    }
                    else
                    {
                        _logger.Info($"无法解析域名: {domain}");
                        // 无法解析不算失败，因为可能是正常的域名不存在情况
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"处理DNS请求时发生错误: {ex.Message}");
                // 异常情况下更新失败计数
                lock (_dnsStatistics)
                {
                    _dnsStatistics.FailedQueries++;
                }
            }
            finally
            {
                // 停止计时并计算响应时间
                stopwatch.Stop();
                double responseTimeMs = stopwatch.Elapsed.TotalMilliseconds;
                
                // 更新统计信息
                if (isSuccess)
                {
                    lock (_dnsStatistics)
                    {
                        // 更新成功计数
                        _dnsStatistics.SuccessfulQueries++;
                        
                        // 更新总响应时间
                        _dnsStatistics.TotalResponseTimeMs += responseTimeMs;
                        
                        // 更新查询类型分布
                        if (!string.IsNullOrWhiteSpace(queryType))
                        {
                            if (_dnsStatistics.QueryTypeDistribution.ContainsKey(queryType))
                            {
                                _dnsStatistics.QueryTypeDistribution[queryType]++;
                            }
                            else
                            {
                                _dnsStatistics.QueryTypeDistribution[queryType] = 1;
                            }
                        }
                    }
                }
                else
                {
                    lock (_dnsStatistics)
                    {
                        // 更新失败计数
                        _dnsStatistics.FailedQueries++;
                    }
                }
            }
        }

        /// <summary>
        /// 处理反向解析请求
        /// </summary>
        /// <param name="reverseDomain">反向域名（如1.0.0.127.in-addr.arpa）</param>
        /// <returns>主机名</returns>
        private async Task<string?> HandleReverseLookupAsync(string reverseDomain)
        {
            try
            {
                // 支持IPv6反向域名（ip6.arpa）：::1 -> localhost
                if (reverseDomain.EndsWith(".ip6.arpa", StringComparison.OrdinalIgnoreCase))
                {
                    var labelPart = reverseDomain.Substring(0, reverseDomain.Length - ".ip6.arpa".Length);
                    var labels = labelPart.Split('.');
                    if (labels.Length == 32 && labels[0] == "1" && labels.Skip(1).All(l => l == "0"))
                    {
                        return "localhost";
                    }
                    // 非 ::1 的 IPv6 反向解析：尝试解析并匹配本地自动生成的PTR记录
                }

                // 解析IPv4反向域名：1.0.0.127.in-addr.arpa -> 127.0.0.1
                var parts = reverseDomain.Split('.');
                if (parts.Length < 6) return null;

                // 提取IP地址部分（反向顺序）
                var ipParts = new List<string>();
                for (int i = 0; i < 4; i++)
                {
                    if (parts.Length > i) ipParts.Add(parts[i]);
                }

                ipParts.Reverse(); // 反转回正常IP顺序
                var ipAddress = string.Join(".", ipParts);

                // 默认反向解析：127.0.0.1 -> localhost
                if (ipAddress == "127.0.0.1")
                {
                    return "localhost";
                }

                // 移除了PTR记录查询逻辑

                // 移除使用泛域名配置管理器进行反向解析的功能

                // 向上游DNS服务器查询反向解析
                return await _upstreamDnsManager.QueryReverseDnsAsync(reverseDomain);
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"处理反向解析失败: {ex.Message}");
                return null;
            }
        }
        #endregion

        #region IDisposable 实现

        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        /// <param name="disposing">是否释放托管资源</param>
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    Stop();
                    // 释放上游DNS管理器
                    _upstreamDnsManager?.Dispose();
                }

                _disposed = true;
            }
        }

        #endregion
    }
}